package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.entity.CategoryBrandRelationEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、读取所有的数据列表
        List<CategoryEntity> listCategoryEntities = this.baseMapper.selectList(null);

        //2、组织成父子关系
        //2.1查询所有一级分类
        List<CategoryEntity> firstLevelCategroies =
                listCategoryEntities.stream()
                        .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                        .map((categoryEntity) -> {
                            categoryEntity.setChildren(getChildren(categoryEntity, listCategoryEntities));
                            return categoryEntity;
                        })
                        .sorted(Comparator.comparingInt(CategoryEntity::getSort))
                        .collect(Collectors.toList());

        return firstLevelCategroies;
    }

    @Override
    public void deleteByIds(List<Long> idList) {
        //TODO 删除之前做验证
        this.baseMapper.deleteBatchIds(idList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> catelogPath = findParentPath(catelogId, paths);

        Collections.reverse(catelogPath);
        return catelogPath.toArray(new Long[catelogPath.size()]);
    }

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    /*
    * 缓存失效模式
    * */
    //@CacheEvict(value = {"categroy"},key = "'getLevel1Categories'")
    @Caching(evict = {
            @CacheEvict(value = {"categroy"},key = "'getLevel1Categories'"),
            @CacheEvict(value = {"categroy"},key = "'getCatalogJson'")
    })
    //@CacheEvict(value = {"categroy"},allEntries = true)
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        if (StringUtils.isNotEmpty(category.getName())) {
            CategoryBrandRelationEntity entity = new CategoryBrandRelationEntity();
            entity.setCatelogName(category.getName());

            UpdateWrapper<CategoryBrandRelationEntity> uw = new UpdateWrapper<>();
            uw.lambda().eq(CategoryBrandRelationEntity::getCatelogId, category.getCatId());

            categoryBrandRelationService.update(entity, uw);

            //TODO 分类 其他关联表
        }
    }

    /*
    * 缓存中有数据，方法不会被调用
    * key默认自动生成，缓存的名字：：SimpleKey[] 自主生成的key值
    * 默认使用jd可序列化机制，将序列化后的数据存到redis
    * 默认ttl时间-1，不符合缓存设计规范
    * 自定义操作
    * 1、key的生成规则：使用key属性指定，接收一个SpEl表达时
    * 2、指定缓存的数据存活时间：配置文件中修改
    * 3、存数据保存为json格式\\
    *RedisCacheConfiguration
    *     *  * */
    @Override
    @Cacheable(value = {"categroy"},key = "#root.method.name")
    public List<CategoryEntity> getLevel1Categories() {
        System.out.println("getLevel1Categories 被调用");
        List<CategoryEntity> categoryEntityList = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>()
                .lambda().eq(CategoryEntity::getParentCid, 0));
        return categoryEntityList;
    }

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Cacheable(value = {"category"},key = "#root.methodName")
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        List<CategoryEntity> allCategories = this.list();
        //查出所有一级分类
        List<CategoryEntity> level1Categories = listByParentId(allCategories, 0L);

        Map<String, List<Catalog2Vo>> mapCatalog2Vos = level1Categories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {

            List<CategoryEntity> level2Categories = listByParentId(allCategories, v.getCatId());
            List<Catalog2Vo> catalog2Vos = null;
            if (level2Categories != null && level2Categories.size() > 0) {
                catalog2Vos = level2Categories.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(),
                            null
                            , l2.getCatId().toString(), l2.getName());

                    List<CategoryEntity> level3Categories = listByParentId(allCategories, l2.getCatId());
                    if (level3Categories != null && level3Categories.size() > 0) {
                        List<Catalog2Vo.Catalog3Vo> catalog3Vos = level3Categories.stream().map(l3 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l3.getParentCid().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(catalog3Vos);
                    }

                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        return mapCatalog2Vos;
    }

    public Map<String, List<Catalog2Vo>> getCatalogJson2() {
        String catalogJson = stringRedisTemplate.opsForValue().get("catalogJson");
        System.out.println("getCatalogJson");
        if (catalogJson == null) {
            RLock lock = redissonClient.getLock("getCatalogJsonLock");
            lock.lock();
            try{
                catalogJson = stringRedisTemplate.opsForValue().get("catalogJson");
                if (catalogJson == null) {
                    Map<String, List<Catalog2Vo>> catalogJsonObject = getCatalogJsonFromDb();
                    stringRedisTemplate.opsForValue().set("catalogJson", JSON.toJSONString(catalogJsonObject));
                    return catalogJsonObject;
                }
            }finally {
                lock.unlock();
            }

        }
        Map<String, List<Catalog2Vo>> catalogJsonObject = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });
        return catalogJsonObject;
    }

    private Map<String, List<Catalog2Vo>> getCatalogJsonFromDb() {
        System.out.println("从数据库查询了数据...");
        //查出所有分类
        List<CategoryEntity> allCategories = this.list();

        //查出所有一级分类
        List<CategoryEntity> level1Categories = listByParentId(allCategories, 0L);

        Map<String, List<Catalog2Vo>> mapCatalog2Vos = level1Categories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {

            List<CategoryEntity> level2Categories = listByParentId(allCategories, v.getCatId());
            List<Catalog2Vo> catalog2Vos = null;
            if (level2Categories != null && level2Categories.size() > 0) {
                catalog2Vos = level2Categories.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(),
                            null
                            , l2.getCatId().toString(), l2.getName());

                    List<CategoryEntity> level3Categories = listByParentId(allCategories, l2.getCatId());
                    if (level3Categories != null && level3Categories.size() > 0) {
                        List<Catalog2Vo.Catalog3Vo> catalog3Vos = level3Categories.stream().map(l3 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l3.getParentCid().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(catalog3Vos);
                    }

                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        return mapCatalog2Vos;
    }

    public List<CategoryEntity> listByParentId(List<CategoryEntity> allCategories, Long parentCid) {
        return allCategories.stream().filter(category -> category.getParentCid().equals(parentCid)).collect(Collectors.toList());
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            this.findParentPath(categoryEntity.getParentCid(), paths);
        }
        return paths;
    }

    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> categories = all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, all));
                    return categoryEntity;
                })
                .sorted(Comparator.comparingInt(CategoryEntity::getSort))
                .collect(Collectors.toList());

        return categories;
    }

}